import 'dart:math' as math;

import 'package:characters/characters.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

/// 解决系统maxlength计算emoj的问题【把emoj,计算时当成两个，限制时当成1个】
/// 如果最后一次复制，超过限制则放弃所有内容，不做裁剪
class BopLengthLimitingTextInputFormatter extends TextInputFormatter {
  /// Creates a formatter that prevents the insertion of more characters than a
  /// limit.
  ///
  /// The [maxLength] must be null, -1 or greater than zero. If it is null or -1
  /// then no limit is enforced.
  BopLengthLimitingTextInputFormatter(this.maxLength)
      : assert(maxLength == null || maxLength == -1 || maxLength > 0);

  final int maxLength;

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue,
      TextEditingValue newValue,
      ) {
    // Return the new value when the old value has not reached the max
    // limit or the old value is composing too.
    if (newValue.composing.isValid) {
      if (maxLength != null  &&
          oldValue.text.length == maxLength) {
        return oldValue;
      }
      return newValue;
    }
    if (maxLength != null && maxLength > 0 && newValue.text.length > maxLength) {
      // If already at the maximum and tried to enter even more, keep the old
      // value.
      return oldValue;
    }
    return newValue;
  }
}